using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Principal;
using System.Security.AccessControl;
using System.IO;

namespace KodeIT.Web.Registration
{
    internal static class Ntfs
    {
        internal static void AddDirectoryACL(string accountName, string directoryName)
        {
            try
            {
                Console.Write(String.Format("ACL: Adding (R)ead, (E)xecute for {0} in {1} ... ",
                    accountName,
                    directoryName));

                NTAccount account = new NTAccount(accountName);
                FileSystemAccessRule rule = new FileSystemAccessRule(
                    account,
                    FileSystemRights.ReadAndExecute,
                    AccessControlType.Allow);

                DirectorySecurity dSecurity = Directory.GetAccessControl(directoryName);

                try
                {
                    dSecurity.AddAccessRule(rule);
                    Directory.SetAccessControl(directoryName, dSecurity);
                    Console.WriteLine("Done");
                }
                catch (IdentityNotMappedException)
                {
                    Console.WriteLine("\n     Account " + accountName + " does not exist, and is ignored.");
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine("\n     Error: " + exp.Message);
            }
        }
    }
}
